package com.example.petstore.controller;

import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.MessageLog;
import com.example.petstore.domain.User;
import com.example.petstore.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.time.LocalDateTime;

@Controller
@SessionAttributes({"loginUser"})
public class ChatController {
    @Autowired
    private MessageService messageService;

    @RequestMapping("/user/chatForm")
    public String chatForm(ModelMap model){
//        User user = (User) model.getAttribute("loginUser");
        return "common/chat";
    }

    /**
     * 获取全部消息
     * @param model
     * @return
     */
    @GetMapping("/user/getMessage")
    @ResponseBody
    public CommonResponse userGetMessage(ModelMap model){
        User user = (User) model.getAttribute("loginUser");
        return messageService.getMessagesByUser(user.getUsername());
    }

    /**
     * 关闭的时候调用，储存离开时间
     * @param model
     * @return
     */
    @GetMapping("/user/closeChat")
    @ResponseBody
    public CommonResponse userCloseChat(ModelMap model) {
        User user = (User) model.getAttribute("loginUser");
        if (user != null) {
            MessageLog messageLog = new MessageLog();
            messageLog.setUserLeftTime(LocalDateTime.now());
            messageLog.setUsername(user.getUsername());

            return messageService.updateMessageLogForUser(user.getUsername(), messageLog);

        } else {
            return CommonResponse.creatForError();
        }
    }
}
